<?php

namespace app\api\library\wechat\getOpenId;

use app\api\help\Http;
use app\api\model\MallWechat;
use think\facade\Db;

/**
 *
 * User: chenzheng
 * Date: 2023/5/8
 * Time: 16:51
 */
class V
{
    public static function run($param)
    {
        $code = $param[ 'code' ];
//        $redirectUrl = $param[ 'redirect' ];
        if (empty($code)) {
            _outPut(1001);
        }
        //获取公众号信息
        $where  = [['id', '=', 1]];
        $wechat = Db::name('mall_wechat')->where($where)->find();
        if (empty($wechat)) {
            _outPut(204, [], '未查询到公众号信息');
        }
        //获取openid
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$wechat['app_id']}&secret={$wechat['app_secret']}&code={$code}&grant_type=authorization_code";
        $res = Http::request($url);
        $res = json_decode($res, true);
        if ( !isset($res[ 'openid' ])) {
            _outPut(1001, [], $res[ 'errmsg' ]);
        }
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$res['access_token']}&openid={$res['openid']}&lang=zh_CN";
        $res = Http::request($url);
        $res = json_decode($res, true);
        if ( !isset($res[ 'openid' ])) {
            _outPut(1001, [], $res[ 'errmsg' ]);
        }
        $info = Db::name('mall_openid')->where('open_id', $res[ 'openid' ])->find();
        if (empty($info)) {
            $addData = [
                'open_id'    => $res[ 'openid' ],
                'nickname'   => $res[ 'nickname' ],
                'sex'        => $res[ 'sex' ],
                'province'   => $res[ 'province' ],
                'city'       => $res[ 'city' ],
                'country'    => $res[ 'country' ],
                'headimgurl' => $res[ 'headimgurl' ],
            ];
            if (false === Db::name('mall_openid')->insert($addData)) {

                _outPut(1001, []);
            }
        }
        $result = [
            'openid' => $res[ 'openid' ],
        ];
        _outPut(200, $result);
    }
}